package com.fyzk.activity.forum;

import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.data.preference.MySharedPreferences;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.RefreshListView;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import com.wf.domain.UrlDef;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

/**
 * Created by fanxs11 on 17/5/12.
 */
@ContentView(R.layout.ac_topicdetail)
public class TopicDetailActivity extends BaseActivity implements RefreshListView.OnRefreshListener {

    private int question_id = 0;

    @ViewInject(R.id.topicdetail_topview)
    private TopTitleView topView;

    @ViewInject(R.id.topicdetail_listview)
    private RefreshListView listView;
    private TopicDetailAdapter adapter;
    private List<TopicDetailBean> infos = new ArrayList<>();
    private boolean requestType = false;    //请求方式：true加载更多，false首次请求或刷新
    private int page = 1;
    private int count = 10;


    @ViewInject(R.id.topicdetail_reply_et)
    private EditText reply_et;

    @ViewInject(R.id.topicdetail_send)
    private TextView send_btn;

    private int answer_id = -1;
    private String sendImgKey = "";

    private InputMethodManager imm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        question_id = getIntent().getIntExtra("id", 0);

        initView();
        getDetail();
        getReplyList(question_id, true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismissSofteKyboard();
    }

    private void initView() {
        topView.setOnTitleClickListener(this);

        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setOnRefreshListener(this);
        adapter = new TopicDetailAdapter(this, infos);
        listView.setAdapter(adapter);
        listView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {

                    dismissSofteKyboard();
                }
                return false;
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < 2) {    // list 下拉刷新和headview
                    return;
                }
                int indext = position - 2;  // infos id
                if (indext < infos.size()) {
                    answer_id = infos.get(indext).getAnswer_id();
                    LogUtil.d("点击item " + indext);
                    reply_et.setHint("评论"+(indext+2)+"楼...");

                    showSofteKyboard();
                }
            }
        });

        adapter.setOnCommentClcikListener(new OnCommentClcikListener() {
            @Override
            public void onClick(int answerId, String userName, int floor) {
                answer_id = answerId;
                reply_et.setHint("评论"+(floor)+"楼...");
                reply_et.setText(""+userName);
                reply_et.setSelection(reply_et.getText().toString().length());
                showSofteKyboard();
            }
        });

        send_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtil.isEmpty(reply_et.getText().toString())) {
                    AppToast.getToast().show("请输入回复内容");
                    return;
                }
                if (answer_id == -1) {  // 回复楼主
                    sendImgKey = System.currentTimeMillis()+"";
                    replyRequest(question_id);
                } else {    // 评论楼层
                    commentRequest(answer_id);
                }
            }
        });
    }

    private void showSofteKyboard() {
        reply_et.requestFocus();
        if (imm == null) {
            imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        }
        imm.showSoftInput(reply_et,InputMethodManager.SHOW_FORCED);
    }

    private void dismissSofteKyboard() {
        answer_id = -1;
        reply_et.setText("");
        reply_et.setHint("回复楼主...");
        if (imm == null) {
            imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        }
        imm.hideSoftInputFromWindow(reply_et.getWindowToken(), 0);
    }

    /**
     *  获取帖子详情（论坛）
     */
    private void getDetail() {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("question_id", question_id);
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_QUESTIONDETAIL);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_QUESTIONDETAIL, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  获取帖子回复列表（论坛）
     */
    private void getReplyList(int question_id, boolean showProgress) {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("question_id", question_id);
            data.put("page", page);
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_REPLYLIST);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_REPLYLIST, params, showProgress);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  回复帖子（论坛）
     */
    private void replyRequest(int question_id) {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("login_user_id", "");
            data.put("question_id", question_id);
            data.put("answer_content", reply_et.getText().toString());
            data.put("attach_ids", new JSONObject());
            data.put("attach_access_key", sendImgKey);
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_REPLY);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_REPLY, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  评论回复（论坛）
     */
    private void commentRequest(int answer_id) {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("login_user_id", "");
            data.put("answer_id", answer_id);
            data.put("message", reply_et.getText().toString());
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_REPLY_ANSWER);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_REPLY_ANSWER, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FORUM_QUESTIONDETAIL:
                TopicListBean bean = JSON.parseObject(resultBean.getData(), TopicListBean.class);
                adapter.setHeadInfo(bean);
                break;
            case CommandUtil.FORUM_REPLYLIST:
                List<TopicDetailBean> beans = JSON.parseArray(resultBean.getData(), TopicDetailBean.class);
                if (requestType) {  // 加载更多
                    if (beans.size() > 0) {
                        infos.addAll(beans);
                        listView.hideFooterView();
                    } else {
                        listView.noMore("无更多评论");
                    }
                } else {
                    infos = beans;
                    listView.hideHeaderView();
                    if (infos.size() == 0) {
                        listView.noMore("暂无评论");
                    } else {
                        listView.hideFooterView();
                    }
                }
                adapter.setInfos(infos);
                requestType = false;
                break;
            case CommandUtil.FORUM_REPLY:
                AppToast.getToast().show("回复成功");
                requestType = false;
                page = 1;
                getReplyList(question_id, false);
                dismissSofteKyboard();
                break;
            case CommandUtil.FORUM_REPLY_ANSWER:
                AppToast.getToast().show("评论成功");
                requestType = false;
                page = 1;
                getReplyList(question_id, false);
                dismissSofteKyboard();
                break;
        }
    }

    @Override
    protected void onFailure(int requestCode) {
        super.onFailure(requestCode);
        if (!requestType) { // 下拉刷新或第一次请求
            infos.clear();
        } else {    // 加载更多
            listView.noMore();

        }
        adapter.setInfos(infos);
    }

    @Override
    public void onDownPullRefresh() {
        page = 1;
        requestType = false;
        getReplyList(question_id, true);
    }

    @Override
    public void onLoadingMore() {
        requestType = true;
        page++;
        getReplyList(question_id, false);
    }

}
